<template lang="pug">
  .siteManage
    Card.siteManage-header
      span 站点名称：
      Input(v-model="siteName",search,enter-button="查询",placeholder='请输入站点名称',:maxlength="50",@on-search='handleUpdateTableData()')
      Button(v-if="$route.meta['/site/add']",@click="handleAddSite") 新增
    Card.siteManage-body
      show-table(ref='tab',:total='total',:current='current',:columns='columns',:data='siteData',@handleChangePage='handleChangePage')
    Modal(v-model="siteModal",:title="modalTitle",@on-cancel='handleCancel').siteManage-modal
      Form(ref="siteForm",:model="formValidate",:rules="ruleValidate",:label-width='92')
        FormItem(label="站点名称：",prop="siteName")
          Input(placeholder='请输入站点名称',v-model="formValidate.siteName",:maxlength="50")
        FormItem(label="域名：",prop="siteDomainName")
          Input(placeholder='请输入域名',v-model="formValidate.siteDomainName",:maxlength="200")
      template(slot="footer")
        template(v-if='modalTitle==="添加站点"')
          Button(@click="handleCancel") 取消
          Button(type='primary',@click="handleAddStation") 确定
        template(v-else)
          Button(@click="handleCancel") 取消
          Button(type="error",v-if="$route.meta['/site/checkin']",:disabled="checkStatus",@click="handleCheckOut") 签出
          Button(type="success",v-if="$route.meta['/site/checkout']",:disabled="!checkStatus",@click="handleCheckIn") 签入
</template>

<script>
import { asyncSite } from '../api'
import showTable from '@/components/show-table/show-table'

export default {
  name: 'SiteManage',
  components: { showTable },
  data() {
    return {
      siteName: '',
      total: 0,
      current: 1,
      siteData: [],
      siteModal: false,
      checkStatus: false,
      modalTitle: '添加站点',
      alterParams: '',
      formValidate: {
        siteName: '',
        siteDomainName: '',
        siteId: ''
      },
      ruleValidate: {
        siteName: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
        siteDomainName: [{ required: true, message: '请输入站点域名', trigger: 'blur' }, { type: 'url', message: '站点域名格式错误,非正确域名格式', trigger: 'blur' }]
      },
      columns: [
        { title: 'ID', width: 60, align: 'center', key: 'siteId' },
        {
          title: '站点名称',
          render: (h, params) => {
            return h(
              'span',
              {
                style: { color: '#2d8cf0', cursor: 'pointer' },
                attrs: {
                  title: `${params.row.siteName}`
                },
                on: {
                  click: () => {
                    this.siteModal = true
                    this.alterParams = params
                    this.modalTitle = '修改站点'
                    params.row.checkType === 0 ? (this.checkStatus = false) : (this.checkStatus = true)
                    ;({ siteName: this.formValidate.siteName, siteDomainName: this.formValidate.siteDomainName, siteId: this.formValidate.siteId } = params.row)
                  }
                }
              },
              params.row.siteName
            )
          }
        },
        {
          title: '域名',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('Tooltip', { attrs: { placement: 'top', content: `${params.row.siteDomainName}` } }, params.row.siteDomainName)
          }
        },
        { title: '创建时间', width: 80, align: 'center', key: 'createTimes' },
        { title: '创建人', width: 150, align: 'center', key: 'creatorName' },
        {
          title: '签出状态',
          width: 150,
          align: 'center',
          key: 'checkType',
          render: (h, params) => {
            switch (params.row.checkType) {
              case 0:
                return h('span', { class: { checkin: true } }, '已签入')
              case 1:
                return h('Tooltip', { attrs: { placement: 'top-start', content: `已签出${params.row.updatePersonName}` } }, [
                  h('span', { class: { checkout: true } }, `已签出${params.row.updatePersonName}`)
                ])
            }
          }
        },
        { title: '签出时间', width: 80, align: 'center', key: 'updateTimes' },
        {
          title: '操作',
          width: 150,
          align: 'center',
          render: (h, params) => {
            let [deleteBtn, dropdownBtn] = ['', '']
            if (this.$route.meta['/site/delete']) {
              deleteBtn = h(
                'Poptip',
                {
                  attrs: { confirm: true, title: '确定要删除这条任务吗', placement: 'top-end', width: '200' },
                  on: { 'on-ok': () => this.handleDeleteSite(params.row.siteId, params.index) }
                },
                [h('span', { style: { color: '#f04134', marginLeft: '25px', cursor: 'pointer' } }, '删除')]
              )
            }
            dropdownBtn = h(
              'Dropdown',
              {
                props: { placement: 'bottom-end' },
                on: {
                  'on-click': name => {
                    this.$router.push({ name: 'site_setting', query: { name: name.toString(), siteId: params.row.siteId, siteName: params.row.siteName } })
                  }
                }
              },
              [
                h('a', [h('span', { style: 'marginRight:5px' }, '详细配置'), h('Icon', { props: { type: 'ios-arrow-down' } })]),
                h('DropdownMenu', { slot: 'list' }, [
                  h('DropdownItem', { props: { name: 1 }, style: { color: '#2d8cf0', cursor: 'pointer' } }, '社保登陆配置'),
                  h('DropdownItem', { props: { name: 2 }, style: { color: '#2d8cf0', cursor: 'pointer' } }, '普通登陆配置')
                ])
              ]
            )
            return h('div', [dropdownBtn, deleteBtn])
          }
        }
      ]
    }
  },
  mounted() {
    this.handleSiteTableData()
  },
  methods: {
    handleChangePage(pageSub) {
      this.handleUpdateTableData(pageSub)
    },
    handleUpdateTableData(current = 1) {
      this.current = current
      this.handleSiteTableData()
    },
    handleSiteTableData: async function() {
      try {
        this.total = 0
        this.siteData = []
        this.$refs['tab'].loading = true
        const res = await asyncSite.list({ data: { siteName: this.siteName, pageIndex: this.current, pageSize: this.$refs['tab'].pageSize } })
        this.total = res.data.data.recordCount
        this.siteData = res.data.data.result
        this.$refs['tab'].loading = false
      } catch (error) {
        this.$refs['tab'].loading = false
      }
    },
    handleAddSite() {
      this.siteModal = true
      this.modalTitle = '添加站点'
    },
    handleCancel() {
      this.siteModal = false
      this.$refs['siteForm'].resetFields()
    },
    handleCheckOut: async function() {
      try {
        await asyncSite.checkout({ data: { siteId: this.formValidate.siteId } })
        this.checkStatus = !this.checkStatus
        this.alterParams.row.checkType = 1
        this.alterParams.row.updatePersonName = sessionStorage.getItem('username')
        this.$Message.success('签出站点成功')
      } catch (error) {}
    },
    handleCheckIn: async function() {
      try {
        const { siteId, siteName, siteDomainName } = this.formValidate
        await asyncSite.checkin({ data: { siteId, siteName, siteDomainName } })
        this.checkStatus = !this.checkStatus
        this.siteModal = false
        this.alterParams.row.checkType = 0
        this.$Message.success('签入站点成功')
      } catch (error) {}
    },
    handleDeleteSite: async function(siteId, index) {
      try {
        await asyncSite.delete({ data: { siteId } })
        this.siteData.splice(index, 1)
        this.handleUpdateTableData(this.siteData.length !== 0 ? this.current : --this.current !== 0 ? this.current : (this.current = 1))
        this.$Message.success('删除成功')
      } catch (error) {}
    },
    handleAddStation() {
      this.$refs['siteForm'].validate(async valid => {
        if (valid) {
          try {
            const { siteName, siteDomainName } = this.formValidate
            await asyncSite.add({ data: { siteName, siteDomainName } })
            this.$Message.success('添加站点成功')
            this.siteModal = false
            this.handleUpdateTableData()
            this.$refs['siteForm'].resetFields()
          } catch (error) {}
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
